// Capitalist City - Business Simulation Game
// Copyright (C) 2011 Azlan Mukhtar
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

#include <QDebug>
#include "game.h"
#include "helper.h"
#include "productsimulation.h"
#include "productui.h"
#include "companyui.h"
#include "company.h"
#include "storeui.h"
#include "gamesettings.h"

CGameSettings *g_Setting;
CLanguage *g_Lang;

Game::Game(Ui::MainWindow *a_ui) :
m_productSim(0),
m_tick(0),
m_companyCounter(0),
gamePaused(false)
{
    mainUi = a_ui;
	uint seed = QDateTime::currentDateTime().toTime_t() * QTime::currentTime().msec();
    qsrand(seed);
    m_productUi = new ProductUi();
    m_companyUi = new CompanyUi();
    m_storeUi = new StoreUi();
    m_storeUi->hide();


    connect(mainUi->actionStart, SIGNAL(toggled(bool)), this, SLOT(on_actionStart_toggled(bool)));
    connect(mainUi->actionCompany,SIGNAL(triggered()),this,SLOT(on_actionCompany_triggered()));
    connect(mainUi->actionStore,SIGNAL(triggered()),this,SLOT(on_actionStore_triggered()));
    connect(mainUi->actionProduct,SIGNAL(triggered()),this,SLOT(on_actionProduct_triggered()));
    connect(m_companyUi->ui->pbAddCompany,SIGNAL(clicked()), this, SLOT(on_pbAddCompany_clicked()));

	Initialize();

}

Game::~Game()
{
    for (int i = 0; i < m_productUiList.size(); ++i) {
        delete m_productUiList.at(i);
    }
    delete vLayout1;
    delete hLayout1;
    delete listWidget;
	delete m_productUi;
	delete m_citySim;
	delete m_productSim;
    delete g_Lang;
}

void Game::Initialize()
{
	// temp codes for testing 
	m_citySim = new CitySimulation;
	m_citySim->AddCity(0, 88, 300000, 1100000, 77, 90);
	m_productSim = new ProductSimulation();

	m_dateTime = QDateTime::fromString("01-01-2000", "dd-MM-yyyy");
	gamePaused = false;

    SetupProductUi();

    mainLayout = new QVBoxLayout();
    mainLayout->addWidget(m_companyUi);
    mainLayout->addWidget(m_storeUi);
    mainUi->widget->setLayout(mainLayout);

	for (int i = 0; i < 4; i++)
		m_productSim->AddProduct(SOAP, Random(40, 100), Random(0, 50),Random(0, 50), Random(500,1500),0,0,Random(300,450),5,0,0,0,0);

	Run();
}

bool Game::Run()
{
    if(m_productSim->isItemDatabaseLoaded) {
		connect(&m_timer, SIGNAL(timeout()), this, SLOT(UpdateTimer()));
		m_timer_interval = 300;
		//m_timer_interval = 0;  //maximum game speed
		m_timer.start(m_timer_interval);
        return true;
	}
	return false;
}

void Game::GameLoop()
{
	UpdateStatusBar();
	m_productSim->CalculateSales(m_citySim->GetCity(0));

	// temp codes for testing
	QMultiMap<quint16, Product*> a_productMap = m_productSim->GetProductMap();
	QList<Item> itemList = m_productSim->GetItemList();
        Product* product;

        int i = 0;
        foreach (Product * iter, a_productMap)
        {
            quint16 key = iter->productType; // map's key = productType
            product = iter;
            m_productUiList.at(i)->SetValues(itemList.at(key).productName, product->saleQuantity,product->rating,product->sellPrice, product->totalCost );
            i++;

            if (i > 3)
                break;
        }
}

void Game::UpdateTimer()
{
	m_tick++;
	if (gamePaused == false)
	{
		GameLoop();
	}
}

void Game::UpdateStatusBar()
{
   
	m_dateTime = m_dateTime.addDays(1); // 1 tick for each day
	QString statusBarMsg = "";
	statusBarMsg += m_dateTime.toString("dd-MM-yyyy");
	statusBarMsg += " - ";
	statusBarMsg += QString::number(m_tick);
    mainUi->statusBar->showMessage(statusBarMsg);
}

void Game::SetupProductUi()
{
    ProductUi *productUi;
    vLayout1 = new QVBoxLayout();
    hLayout1 = new QHBoxLayout();
    listWidget = new QListWidget();

    for (int i = 0; i < 4; i++)
    {
        productUi = new ProductUi();
        m_productUiList.append(productUi);
        vLayout1->addWidget(m_productUiList.at(i));
    }
    hLayout1->addWidget(listWidget);
    hLayout1->addLayout(vLayout1);
    //ui->widget->setLayout(hLayout1);
}


void Game::on_actionStart_toggled(bool checked)
{
    Q_UNUSED(checked);
    gamePaused = !gamePaused;
    if (gamePaused)
    {
        m_timer.stop();
    }
    else
    {
        m_timer.start(m_timer_interval);
    }
}

void Game::on_actionCompany_triggered()
{
    m_storeUi->hide();
    m_companyUi->show();
}

void Game::on_actionStore_triggered()
{
    m_companyUi->hide();
    m_storeUi->show();
}

void Game::on_actionProduct_triggered()
{
    m_companyUi->hide();
    m_storeUi->hide();
   // ShowProducts();
}

void Game::on_pbAddCompany_clicked()
{
    Company *company = new Company();
    m_companyList.append(company);
    company->companyName = QString("Company ") + QString::number(m_companyCounter);
    company->companyId = m_companyCounter;
    m_companyCounter++;
}
